package com.gaga.common.utils;

/**
 * @DESCRIPTION:
 * @USER: ningxiang
 * @DATE: 4/26/2025 11:36 PM
 */

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;

public class AESKeyManager {
    private static final String KEY_ALGORITHM = "AES";
    private static final int KEY_SIZE = 256; // 支持 128/192/256

    /**
     * 生成固定密钥（基于密码）并保存到文件
     */
    public static SecretKey generateFixedKey(String password, Path keyFile) throws Exception {
        // 使用 PBKDF2 安全生成密钥
        byte[] salt = new byte[16]; // 固定盐值（可根据需求修改）
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, KEY_SIZE);
        SecretKey tmpKey = factory.generateSecret(spec);
        SecretKey secretKey = new SecretKeySpec(tmpKey.getEncoded(), KEY_ALGORITHM);

        // 保存密钥到文件
        Files.write(keyFile, secretKey.getEncoded());
        return secretKey;
    }

    /**
     * 从文件加载固定密钥
     */
    public static SecretKey loadFixedKey(Path keyFile) throws Exception {
        byte[] keyBytes = Files.readAllBytes(keyFile);
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }

    /**
     * 验证密钥是否符合 AES 长度要求
     */
    public static void validateKey(SecretKey key) throws NoSuchAlgorithmException {
        int length = key.getEncoded().length * 8;
        if (length != 128 && length != 192 && length != 256) {
            throw new NoSuchAlgorithmException("Invalid AES key length: " + length + " bits");
        }
    }
}
